<?php
namespace App\Http\Controllers;

use App\Exceptions\ValidateException;
use App\Model\Shopping;
use Illuminate\Http\Request;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-03-09 11:58
 *
 * @Description:
 */
class PaymentController extends Controller
{
    /**
     * 微信支付
     */
    const WEI_CHAT = 'http://www.payment.loc/weiChat/';

    /**
     * 支付宝支付
     */
    const ALI_PAY = 'http://www.payment.loc/aliPay/';

    /**
     * @var Request
     */
    protected $request;

    /**
     * PaymentController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function payment()
    {
        try {
            $data['outTradeNo'] = date('mdHis') . mt_rand(100, 1000);
            $data['subject'] = '象米国际直营店';
            $data['totalAmount'] = $this->request->input('totalAmount');
            $data['authCode'] = $this->request->input('authCode');
            $payType = $this->request->input('payType');
            if (empty($data['totalAmount']) || empty($data['authCode']) || empty($payType)) {
                return $this->fail('参数错误');
            }
            switch ($payType) {
                case Shopping::BANK_CARD:
                    $result = $this->backPay($data);
                    break;
                case Shopping::WE_CHAT:
                    $result = $this->weiChatPay($data);
                    break;
                case Shopping::PAY_PAL:
                    $result = $this->aliPay($data);
                    break;
                default:
                    $result = ['data' => [], 'message' => ''];
                    break;
            }

            return $this->success($result['data'], $result['message']);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    protected function backPay(array $data)
    {
        return [
            'data' => [
                'outTradeNo' => $data['outTradeNo'],
                'authCode' => $data['authCode'],
                'tradeNo' => 0
            ],
            'message' => 'Success'
        ];
    }

    protected function weiChatPay(array $data)
    {
        $result = $this->post(self::WEI_CHAT, $data);

        return [
            'data' => [
                'outTradeNo' => $data['outTradeNo'],
                'authCode' => $data['authCode'],
                'tradeNo' => isset($result['transaction_id'])?$result['transaction_id']:0
            ],
            'message' => $result['result_code'] === 'SUCCESS'?'Success':'Fail'
        ];
    }

    protected function aliPay(array $data)
    {
        $result = $this->post(self::ALI_PAY, $data);

        return [
            'data' => [
                'outTradeNo' => $data['outTradeNo'],
                'authCode' => $data['authCode'],
                'tradeNo' => isset($result['trade_no'])?$result['trade_no']:0
            ],
            'message' => $result['msg'] === 'Success'?'Success':'Fail'
        ];
    }

    protected function post($url, $data, $timeOut = 30)
    {
        $header = ['Content-Type: application/json'];
        $process = curl_init($url);
        curl_setopt($process, CURLOPT_HTTPHEADER, $header);
        curl_setopt($process, CURLOPT_TIMEOUT, $timeOut);
        curl_setopt($process, CURLOPT_CONNECTTIMEOUT, $timeOut);
        curl_setopt($process, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($process, CURLOPT_POST, 1);
        $result = curl_exec($process);
        curl_close($process);

        return json_decode($result, true);
    }
}